<?php
namespace app\service;

use app\model\GoodsConcernModel;
use app\model\GoodsModel;
use app\model\GoodsPeriodModel;
use app\model\MemberModel;
use app\model\mongo\OrderReviewMongo;
use app\model\OrderReviewModel;
use const support\CORRECT;
use const support\DENY;

class GoodsService
{

    //获取推荐列表
    public static function getPushLists(): array
    {
        //获取商品列表
        $goods=GoodsModel::where([
            'status'    =>CORRECT,
            'is_push'   =>CORRECT,
            'is_audit'  =>CORRECT,
            'is_upper'  =>CORRECT
        ])->select([
            'id','goods_sn','goods_icon','goods_title','goods_sale_num',
            'goods_appropriate_age','is_enroll_period','is_deadline','goods_end_time',
            'goods_recommend_reason','goods_activity_cycle','location_province','location_city',
            'location_area','goods_labels'
        ])->with([
            'goodsSpecifications:type,goods_id,goods_sale_price,goods_original_price'
        ])->get()->append(['goods_end_status'])->toArray();
        foreach ($goods as &$good){
            //满意度
            $good['review_satisfaction_rate']=OrderReviewService::reviewSatisfactionCalculate($good['id']);
            $goodsSpecificationPrices=array_column($good['goods_specifications'],'goods_sale_price');
            $num=$goodsSpecificationPrices?count(array_values(array_unique($goodsSpecificationPrices))):0;
            $good['goods_sale_price']='';
            if ($num>1){
                $good['is_same_price']=DENY;
            }else{
                $good['is_same_price']=CORRECT;
                $good['goods_sale_price']=$goodsSpecificationPrices[0]??'';
            }
        }
        return $goods;
    }

    //获取商品名称
    public static function getGoodsTitles(): array
    {
        return GoodsModel::where([
            'status'    =>CORRECT,
            'is_audit'  =>CORRECT
        ])->pluck('goods_title')->toArray();
    }

    //获取商品列表
    public static function getLists($page,$limit,$cateId): array
    {
        //获取本次查询涉及分类ID
        $cateIds=[];
        if ($cateId){
            $cates=GoodsCateService::getCateIdsByFid([$cateId]);
            $cateIds=array_column($cates,'id');
        }
        $goods=GoodsModel::where([
            'status'    =>CORRECT,
            'is_audit'  =>CORRECT,
            'is_upper'  =>CORRECT
        ]);
        if ($cateIds){
            $goods=$goods->whereIn('goods_cate',$cateIds);
        }
        //计算总数量
        $totalNum=$goods->count();
        $offset=($page-1)*$limit;
        $goods=$goods->select([
            'id','goods_sn','goods_icon','goods_title','goods_sale_num',
            'goods_appropriate_age','is_enroll_period','is_deadline','goods_end_time',
            'goods_recommend_reason','goods_activity_cycle','location_province','location_city',
            'location_area','goods_labels'
        ])->offset($offset)->limit($limit)->with([
            'goodsSpecifications:type,id,goods_id,goods_sale_price,goods_original_price'
        ])->orderBy('sort','desc')->get()->append(['goods_end_status'])->toArray();
        foreach ($goods as &$good){
            //满意度
            $good['review_satisfaction_rate']=OrderReviewService::reviewSatisfactionCalculate($good['id']);
            $goodsSpecificationPrices=array_column($good['goods_specifications'],'goods_sale_price');
            $num=$goodsSpecificationPrices?count(array_values(array_unique($goodsSpecificationPrices))):0;
            $good['goods_sale_price']='';
            if ($num>1){
                $good['is_same_price']=DENY;
            }else{
                $good['is_same_price']=CORRECT;
                $good['goods_sale_price']=$goodsSpecificationPrices[0]??'';
            }
        }
        return commonPagingData($goods,$page,$limit,$totalNum);
    }

    //获取商品详情
    public static function getDetails(int $memberId,int $goodsId): array
    {
        $goods=GoodsModel::where([
            'id'        =>$goodsId,
            'status'    =>CORRECT,
            'is_audit'  =>CORRECT,
            'is_upper'  =>CORRECT
        ])->with([
            'goodsSpecifications:type,id,goods_id,goods_sale_price,goods_original_price',
            'goodsImages:id,goods_id,goods_image',
            'goodsPeriods:id,goods_id,goods_period_title,goods_period_date,goods_stock_num',
            'assemblyLocation:id,location_province,location_city,location_area,location_address,contacts_name,contacts_mobile'
        ])->get()->append(['goods_end_status'])->makeHidden([
            'is_audit','update_time','is_allocation_mode','allocation_rate','allocation_amount','is_repurchase_allocation_mode',
            'repurchase_allocation_rate','repurchase_allocation_amount','assembly_location_id'
        ])->first();
        if (empty($goods->id)){
            return [];
        }
        $goods=$goods->toArray();
        $isDisable=CORRECT;
        //对商品营期进行限制
        if (!empty($goods['goods_periods'])){
            foreach ($goods['goods_periods'] as &$goodsPeriod){
                $goodsPeriod['is_disable']=(($goodsPeriod['goods_period_date']-24*3600)>time() || $goodsPeriod['goods_stock_num']==0)?DENY:CORRECT;
                if ($goodsPeriod['is_disable']==DENY){
                    $isDisable=DENY;
                }
            }
        }
        $goods['is_disable']=$isDisable;
        //关注人数信息
        $concernMemberIds=GoodsConcernModel::where([
            'goods_id'=>$goodsId,
            'status'  =>CORRECT
        ])->pluck('member_id')->toArray();
        $goods['goods_concern_num']=count($concernMemberIds);
        $goods['goods_concern_avatar']=[];
        if ($goods['goods_concern_num']){
            $goods['goods_concern_avatar']=MemberModel::whereIn('id',$concernMemberIds)->orderBy('id','desc')->limit(8)
                ->pluck('avatar')->toArray();
        }
        //评论信息
        $goods['review_num']=OrderReviewModel::where(['goods_id'=>$goodsId,'status'=>CORRECT])->count();
        $goods['review_lists']=OrderReviewService::getReviews($goodsId,1,2);
        $goods['review_satisfaction']=[
            'rate'  =>OrderReviewService::reviewSatisfactionCalculate($goodsId),
            'lists' =>OrderReviewService::getReviewScoreRates($goodsId)
        ];
        $goodsSpecificationPrices=array_column($goods['goods_specifications'],'goods_sale_price');
        $num=$goodsSpecificationPrices?count(array_values(array_unique($goodsSpecificationPrices))):0;
        $goods['goods_sale_price']='';
        if ($num>1){
            $goods['is_same_price']=DENY;
        }else{
            $goods['is_same_price']=CORRECT;
            $goods['goods_sale_price']=$goodsSpecificationPrices[0]??'';
        }
        //获取商品收藏状态
        $goodsConcernStatus=GoodsConcernModel::where([
            'member_id'=>$memberId,
            'goods_id' =>$goodsId,
            'status'   =>CORRECT
        ])->value('id')?:false;
        $goods['is_concern']=$goodsConcernStatus?CORRECT:DENY;
        return $goods;
    }

    /**
     * 关注或取消关注操作
     * @param $memberId
     * @param $goodsId
     * @param $isConcern
     * @return bool|int
     */
    public static function toGoodsConcernStatus($memberId,$goodsId, $isConcern)
    {
        $model=GoodsConcernModel::where([
            'member_id'=>$memberId,
            'goods_id' =>$goodsId,
        ])->first();
        if (empty($model->id)){
            $insert=[
                'member_id'=>$memberId,
                'goods_id' =>$goodsId,
                'status'   =>$isConcern,
                'create_time'=>time()
            ];
            $ret=GoodsConcernModel::insertGetId($insert);
        }else{
            $model->status=$isConcern;
            $model->update_time=time();
            $ret=$model->save();
        }
        return $ret;
    }

    //商品活动列表
    public static function activityGoodsList(int $monthTime,int $dayTime=0): array
    {
        //查询符合营期商品ID组
        $model=GoodsPeriodModel::where([
            'status'=>CORRECT
        ]);
        if ($dayTime){
            $dayTime=strtotime(date('Y-m-d', $dayTime));
            $model=$model->where('goods_period_date',$dayTime);
        }else{
            //计算出本月的起始时间
            $endOfMonthTimestamp = strtotime('last day of', $monthTime);
            $model=$model->whereBetween('goods_period_date',[$monthTime,$endOfMonthTimestamp]);
        }
        $goodsIds=$model->pluck('goods_id')->toArray();
        $goodsIds=$goodsIds?array_values(array_unique($goodsIds)):[];
        $goods=GoodsModel::where([
            'status'    =>CORRECT,
            'is_audit'  =>CORRECT,
            'is_upper'  =>CORRECT
        ])->whereIn('id',$goodsIds);
        //计算总数量
        $totalNum=$goods->count();
        $goods=$goods->select([
            'id','goods_sn','goods_icon','goods_title','goods_sale_num',
            'goods_appropriate_age','is_enroll_period','is_deadline','goods_end_time',
            'goods_recommend_reason','goods_activity_cycle','location_province','location_city',
            'location_area','goods_labels'
        ])->with([
            'goodsSpecifications:type,id,goods_id,goods_sale_price,goods_original_price'
        ])->orderBy('sort','desc')->get()->append(['goods_end_status'])->toArray();
        foreach ($goods as &$good){
            //满意度
            $good['review_satisfaction_rate']=OrderReviewService::reviewSatisfactionCalculate($good['id']);
            $goodsSpecificationPrices=array_column($good['goods_specifications'],'goods_sale_price');
            $num=$goodsSpecificationPrices?count(array_values(array_unique($goodsSpecificationPrices))):0;
            $good['goods_sale_price']='';
            if ($num>1){
                $good['is_same_price']=DENY;
            }else{
                $good['is_same_price']=CORRECT;
                $good['goods_sale_price']=$goodsSpecificationPrices[0]??'';
            }
        }
        return commonPagingData($goods,1,1000,$totalNum);
    }

    //获取日历事件
    public static function getGoodsActivityEventDate(int $monthTime): array
    {
        //获取符合规范的商品
        $goodsIds=GoodsModel::where([
            'status'    =>CORRECT,
            'is_audit'  =>CORRECT,
            'is_upper'  =>CORRECT
        ])->pluck('id')->toArray();
        //查询符合营期商品ID组
        $model=GoodsPeriodModel::where([
            'status'=>CORRECT
        ])->whereIn('goods_id',$goodsIds);
        //计算出本月的起始时间
        $firstDayOfMonth = strtotime(date('Y-m-01', $monthTime));
        $endOfMonthTimestamp = strtotime('last day of', $monthTime);
        $model=$model->whereBetween('goods_period_date',[$firstDayOfMonth,$endOfMonthTimestamp]);
        $goodsPeriodDates=$model->pluck('goods_period_date')->toArray();
        $numberOfDays = date('j', $endOfMonthTimestamp);
        $data=[];
        for ($i=0;$i<$numberOfDays;$i++){
            //计算今日起始时间戳
            $time=$firstDayOfMonth+86400*$i;
            $data[]=[
                'date'=>date('Y-m-d',$time),
                'num' =>$i+1,
                'time'=>$time,
                'is_stroke'=>in_array($time,$goodsPeriodDates)?CORRECT:DENY
            ];
        }
        return $data;
    }

}